package sdk.webview.fmc.com.fmcsdk.activity;

import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.NfcA;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.Settings;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.base.BaseActivity;
import sdk.webview.fmc.com.fmcsdk.base.BasePresenter;
import sdk.webview.fmc.com.fmcsdk.util.TitleBar;
import sdk.webview.fmc.com.fmcsdk.util.Utility;
import sdk.webview.fmc.com.fmcsdk.util.nfc.ParsedNFCRecord;
import sdk.webview.fmc.com.fmcsdk.view.GifView;

public class NFCActivity extends BaseActivity {


    private static final int REQUEST_CODE = 12;

    TitleBar titlebar;
    TextView tvNfcMessage;
    ImageView ivScan;
    TextView tvScanContent;
    TextView tvWrite;
    private NfcAdapter mNfcAdapter;
    private PendingIntent mPendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_nfc;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        titlebar = (TitleBar) findViewById(R.id.titlebar);
//        ImageView iv_gif = (ImageView) findViewById(R.id.iv_gif);
//        Glide.with(context).load(R.drawable.nfc).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE)
//                .into(iv_gif);
        GifView gifImageView = (GifView) findViewById(R.id.iv_gif);
        gifImageView.setGifResource(R.drawable.nfc);
        tvNfcMessage = (TextView) findViewById(R.id.tv_nfc_message);
        ivScan = (ImageView) findViewById(R.id.iv_scan);
        tvScanContent = (TextView) findViewById(R.id.tv_scan_content);
        tvWrite = (TextView) findViewById(R.id.tv_write);
        titlebar.setTitle(getString(R.string.nfc_setting));
        ivScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utility.startScanActivity(NFCActivity.this, REQUEST_CODE);
            }
        });
        setNFCAdapter();
    }

    //设置NFC基本配置
    private void setNFCAdapter() {
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        try {
            ndef.addDataType("*/*");
        } catch (IntentFilter.MalformedMimeTypeException e) {
            throw new RuntimeException("fail", e);
        }
        mFilters = new IntentFilter[]{ndef,};
        // 根据标签类型设置
        mTechLists = new String[][]{new String[]{NfcA.class.getName()}};
        checkNFCFunction();
    }

    //检查是否具有NFC功能和是否开启了NFC
    private void checkNFCFunction() {
        if (mNfcAdapter != null) {
            tvNfcMessage.setVisibility(View.GONE);
            if (!mNfcAdapter.isEnabled()) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(getString(R.string.remind));
                builder.setMessage(getString(R.string.want_to_nfc));
                builder.setPositiveButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                Intent setnfc = new Intent(Settings.ACTION_NFC_SETTINGS);
                                startActivity(setnfc);
                            }
                        });
                builder.setNegativeButton(android.R.string.cancel, null);
                builder.show();

            }
        } else {
            tvNfcMessage.setVisibility(View.VISIBLE);
        }

    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (!TextUtils.isEmpty(getText(tvScanContent))) {
            if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
                Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                //老系统招商项目等NFC返回值开头带有0和1的处理方法
//                boolean b = ParsedNFCRecord.writeTag(tag, "1"+getText(tvScanContent));
                boolean b = ParsedNFCRecord.writeTag(tag, getText(tvScanContent));
                if (b) {
                    ToastMessage(R.string.write_success);
                    Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
                    if (messages != null && messages.length > 0) {
                        NdefMessage message = (NdefMessage) messages[0];
                        String content = ParsedNFCRecord.readTag(message);
                        if (!TextUtils.isEmpty(content)) {
                            SpannableString spannableString = new SpannableString("写入成功,"+getText(tvScanContent));
                            spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#FF47b879")), 0,5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            tvWrite.setText(spannableString);

                        } else {
                            ToastMessage(R.string.label_is_empty);
                        }
                    }
                } else {
                    ToastMessage(R.string.write_failure);
                }
            }
        } else {
            ToastMessage(R.string.scan_content_is_empty);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE) {
                String result = data.getStringExtra(CaptureActivity.SCAN_RESULT);
                if (TextUtils.isEmpty(result)) {
                    tvScanContent.setText(getString(R.string.scan_content_is_empty));
                } else {
                    tvScanContent.setText(result);
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        // TODO 自动生成的方法存根
        super.onResume();
        enableForegroundDispatch();
    }

    private void enableForegroundDispatch() {
        // TODO 自动生成的方法存根
        if (mNfcAdapter != null) {
            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        disableForegroundDispatch();
    }

    private void disableForegroundDispatch() {
        // TODO 自动生成的方法存根
        if (mNfcAdapter != null) {
            mNfcAdapter.disableForegroundDispatch(this);
        }
    }

}
